from .base import BaseConfig
from lib.conf.config import settings


class Memory(BaseConfig):

    def process(self, command_func, debug):
        if debug:
            with open(settings.BASE_DIR + '/files/memory.out', 'r', encoding='utf-8') as f:
                output = f.read(65535)
        else:
            output = command_func("sudo dmidecode  -q -t 17 2>/dev/null")
        return self.parse(output)

    def parse(self, content):
        """
        解析shell命令返回结果
        :param content: shell 命令结果
        :return:解析后的结果
        """
        ram_dict = {}
        key_map = {
            'Size': 'capacity',                 # 内存大小
            'Locator': 'slot',                  # 内存槽位
            'Type': 'model',                    # 内存类型
            'Speed': 'speed',                   # 内存速率
            'Manufacturer': 'manufacturer',     # 内存厂商
            'Serial Number': 'sn',              # 内存SN

        }
        devices = content.split('Memory Device')
        for item in devices:
            item = item.strip()
            if not item:
                continue
            if item.startswith('#'):
                continue
            segment = {}
            lines = item.split('\n\t')
            for line in lines:
                if not line.strip():
                    continue
                if len(line.split(':')):
                    key, value = line.split(':')
                else:
                    key = line.split(':')[0]
                    value = ""
                if key in key_map:
                    segment[key_map[key.strip()]] = value.strip()

            ram_dict[segment['slot']] = segment

        return ram_dict